<?php
function d($url,$delayTime=0){
	myresponse::redirect($url,$delayTime);
}

function jsonPrettyString($json){
    return json_encode($json,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);
}

function hide($str, $replace="****", $posOpen=1, $posClose=4) {

	if(!$str) return "";//空的直接返回空

	if(is_array($str)) return $str;

	if(preg_match("/\d{11}/",$str)){
		return substr_replace($str,'****',2,10);
	}

	return mb_substr($str, 0, $posOpen).$replace.mb_substr($str, $posClose+1);
}

/**
 * 此处提供了对框架进行快速存取的方法和其他的公用函数。
 * 
 * */

function tidyJson($data){
	return str_replace('\/','/',json_encode($data));
}

function j($arr){
	die(json_encode($arr));
}

/**
 * URL base64解码
 * '-' -> '+'
 * '_' -> '/'
 * 字符串长度%4的余数，补'='
 * @param String $string
 * @return String
 */
function urlsafe_b64decode($string) {
	$data = str_replace(array('-','_'),array('+','/'),$string);
	$mod4 = strlen($data) % 4;
	if ($mod4) {
		$data .= substr('====', $mod4);
	}
	return base64_decode($data);
}

/**
 * URL base64编码
 * '+' -> '-'
 * '/' -> '_'
 * '=' -> ''
 * @param String $string
 * @return String
 */
function urlsafe_b64encode($string) {
	$data = base64_encode($string);
	$data = str_replace(array('+','/','='),array('-','_',''),$data);
	return $data;
}


/**
 * 将url链接转换为系统安全的
 * */
function my_urlencode($url){
	$tmpUrl = str_replace('http:','-.-a',$url);
	$tmpUrl = str_replace('/','-.-b',$tmpUrl);
	$tmpUrl = str_replace(',','-.-c',$tmpUrl);
	$tmpUrl = str_replace('?','-.-d',$tmpUrl);
	$tmpUrl = urlencode($tmpUrl);
	return $tmpUrl.',uk,'.md5(URL_KEY1.$url.URL_KEY2);
}

/**
 * 校验URL链接是否合法
 * */
function my_urlidenty($url){
	$key = g('uk');
	if(md5(URL_KEY1.$url.URL_KEY2) == $key){
		return true;
	}
	return false;
}

/**
 * 将url链接转换回去
 * */
function my_urldecode($url){
	$tmpUrl = urldecode($url);
	$tmpUrl = str_replace('-.-d','?',$tmpUrl);
	$tmpUrl = str_replace('-.-c',',',$tmpUrl);
	$tmpUrl = str_replace('-.-b','/',$tmpUrl);
	$tmpUrl = str_replace('-.-a','http:',$tmpUrl);
	return $tmpUrl;
}

/**
 * 在web端安全显示数据
 * @param $str String
 * */
function show($str){
	echo htmlspecialchars(htmlspecialchars_decode($str));
}

function db($forceNew = false){
	global $db;
	if(is_object($db)){
		return $db;
	}else{
		$db = new mydb();
		return $db;
	}
}

/**
 * 获得get传参
 * */
function g($varname,$deault = null){
	global $request;
	return $request->g($varname,$deault);
}

//是否通过$_REQUEST和,设置某个参数
function s($varName,$data=''){
	if($data){
		if(array_key_exists($varName,$data)) {
			return true;
		}
		return false;
	}
	global $request;
	return $request->s($varName);
}

/**
 * 获得post传参
 * */
function p($varname){
	return myrequest::p($varname);
}

/**
 * 获得COOKIE传参
 * @return COOKIE值
 * */
function c($varname){
	return myrequest::c($varname);
}


/**
 * 获得REQUEST传参
 * */
function r($varname){
	global $request;
	return $request->r($varname);
}



/**
 * 获得REQUEST传参
 * */
function r_int($varname){
	global $request;
	if(is_int($varname)) j(["code"=>-200,"info"=>"参数错误",'r_int'=>$varname]);
	return intval($request->r($varname));
}


/**
 * 获得原始的get和post数据
 * */
function decode($str){
	global $request;
	return $request->decode($str);
}


/**
 * 是否为合法的email
 * */
function is_email($email){
	if(strlen($email) <= 5 ) return false;
	if(preg_match("/.*?@.+?/",$email)){
		return true;
	}
	return false;
}


/**
 	 * 将数组复权，获得复权后的数组值
 	 * @param $field_values Array 需要进行复权的数组
 	 * @param  $is_negative Bool 是否需要将数组的权值颠倒
 	 * @param $is_percent Bool 是否要讲复权值转化为百分比
 	 * @return Array 数组
 	 * 
	 * */
function fuquan($field_values,$is_negative=false,$is_percent=false){
	$max_field_values = max($field_values);
	$min_field_values = min($field_values);
	$change_field_values = $max_field_values - $min_field_values;
	$avg_field_values    = array_sum($field_values)/count($field_values);
	$tempNum = count($field_values);
	for($i = 0; $i < $tempNum; $i++){ //获得新的大买变化波动率
		if($change_field_values == 0 ){//如果没有波动，复权后为0
			$field_values[$i] = 0;
		}else{
			if($is_negative){//需要将权重颠倒
				$field_values[$i] = - round(($field_values[$i]-$avg_field_values)/$change_field_values,3) * 100;
			}else {
				$field_values[$i] = round(($field_values[$i]-$avg_field_values)/$change_field_values,3) * 100 ;
			}
		}
	}

	//---计算百分比--------------------
	if($is_percent){
		$min_value = min($field_values);
		for($i = 0; $i < count($field_values); $i++){
			$field_values[$i] = $field_values[$i] + abs($min_value) + abs($min_value/2);
		}


		$sum = array_sum($field_values);
		for($i = 0; $i < count($field_values); $i++){
			$field_values[$i] = round($field_values[$i] / $sum * 100,1);
		}
	}

	return $field_values;
}

/**
 * 将日期数组进行复权
 * @param Array $trueDays
 * @return Array
 * */
function fuquan_day($trueDays){
	$curYear  = '';
	$preYear  = '';
	$curMonth = '';
	$preMonth='';
	for($i = 0; $i < count($trueDays); $i++){
		$curDay = $trueDays[$i];
		$curMonth = substr($curDay,4,2);//日期转义
		$curYear  = substr($curDay,0,4);
		if($curYear != $preYear){
			$dayValue = floatval('0.'.$curDay);//完整的年月日
			$preYear = $curYear;
			$preMonth = $curMonth;
		}else if($curMonth!= $preMonth){
			//$dayValue = floatval('0.'.substr($curDay,2));//加入年份
			$dayValue = floatval('0.'.$curMonth);//加入年份
			$preMonth = $curMonth;
		}else{
			$dayValue = floatval('0.'.substr($curDay,6));
		}
		$fuquanDays[] = $dayValue;
	}
	return $fuquanDays;
}

/**
 * 格式化输出
 * */
function print_var($var){
	echo "<br />";
	print_r($var);
	echo "<br />";
}




/**
 * 获取某一天的破浪股指
 * @param Date $day (2009-02-18 or 20090228 )
 * @param Resource $db
 * @return Float $pigIndex
 * 
 * */
function get_pig_index( $day ,$db,$table='tbl_stock_duck',$dateField='FDate',$indexField='FDuckIndex' ){
	static $gAllPigIndex; //缓存全部破浪股指
	if(empty($gAllPigIndex)){//缓存所有的破浪指数
		$gAllPigIndex = array();
		$gAllPigIndex['index'] = array();
		$gAllPigIndex['date']  = array();

		$sql = 'SELECT * FROM '.$table.' ORDER BY '.$dateField.' ASC';
		$result = $db->query($sql);
		foreach ($result as $row){
			$gAllPigIndex['index'][$row[$dateField]] = $row[$indexField];
			$gAllPigIndex['date'][] = $row[$dateField];
		}
	}

	$num = count($gAllPigIndex['date']);
	for($i = 0; $i < $num; $i++){//從前往後順序查找第一個等於或者大於$day的日期//@todo 用折半查找提高效率
		$curDate = $gAllPigIndex['date'][$i];
		if($curDate == $day){
			return $gAllPigIndex['index'][$curDate];
		}elseif($curDate>$day) {
			if(($i-1) < 0){
				return $gAllPigIndex['index'][$gAllPigIndex['date'][$i]];
			}else{
				return $gAllPigIndex['index'][$gAllPigIndex['date'][$i-1]];
			}
		}
	}
	//沒有找到這樣的值,所有鴨指日期均小於$day，則返回最大的date
	return $gAllPigIndex['index'][$gAllPigIndex['date'][$num-1]];

}



/**
 * 获取一个数组的中段数值的平均值，如果小于等于3，则返回数组的平均值
 * @param  Array $array
 * @return Array $avgArray
 * */
function get_middle_avg($array){
	$avgArray = array( //返回数组的结构
	'avg_value' =>0,  //均值
	'valid_num' =>0,  //均值来源数
	'skip_num'  =>0   //跳过的无效数据数量
	);


	sort($array);
	$num = count($array);
	if($num <= 3){
		$avgArray = array(
		'avg_value' =>array_sum($array)/$num,
		'valid_num' =>$num,
		'skip_num'  =>0
		);
	}else {
		$floorNum = floor($num /3);
		$ceilNum  = ceil($num /3 );
		$total = 0;
		for($i = $floorNum; $i < ($floorNum + $ceilNum); $i++){
			$total += $array[$i];
		}
		$avgArray = array(
		'start_pos' =>$floorNum,
		'end_pos'   =>$floorNum + $ceilNum -1,
		'avg_value' =>$total/$ceilNum,
		'valid_num' =>$ceilNum,
		'skip_num'  =>$num-$ceilNum
		);
	}

	return $avgArray;
}

 

/**
 * 将数组中的所有字符串转换为另外一种编码方式
 * @param STring src_charset
 * @param String target_charset
 * @param Array src_array
 * @return Array 
 * */
function iconv_array($src_charset,$target_charset,$src_array){
	$resultArray = array();
	for($i = 0; $i < count($src_array); $i++){
		$resultArray[$i] = mb_convert_encoding($src_array[$i],$target_charset,$src_charset);
	}
	return $resultArray;
}


/**
 * 将数组中所有的元素值空白去掉
 * @param Array $array 源数组
 * @return Array  $resultArray
 * */
function trim_array($array){
	$resultArray = array();
	for($i = 0; $i < count($array); $i++){
		$resultArray[$i] = trim($array[$i]);
	}
	return $resultArray;
}

/**
 * 安全打印用户数据
 * */
function safeEcho($str){
	echo htmlspecialchars($str);
}


function fixtags ($text) {
$text = htmlspecialchars($text);
$text = preg_replace("/&quot;/", "&quot;\"", $text);
$tags = "/&lt;(!|)(\/|)(\w*)(\ |)(\w*)([\\\=]*)(?|(\")\"&quot;\"|)(?|(.*)?&quot;(\")|)([\ ]?)(\/|)&gt;/i";
$replacement = "<$1$2$3$4$5$6$7$8$9$10$11>";
$text = preg_replace($tags, $replacement, $text);
$text = preg_replace("/=\"\"/", "=", $text);
$text = preg_replace("/&quot;\"/", "\"", $text);
return $text;
}

function safe_strip($string,$remindTags=''){
	return strip_tags(fixtags($string), $remindTags);
}
//使用方法：
//strip_tags(fixtags($string), '<div>');

function arraytoxml($data){
	$str='<xml>';
	foreach($data as $k=>$v) {
		$str.='<'.$k.'>'.$v.'</'.$k.'>';
	}
	$str.='</xml>';
	return $str;
}
function xmltoarray($xml) {
	//禁止引用外部xml实体
	libxml_disable_entity_loader(true);
	$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
	$val = json_decode(json_encode($xmlstring),true);
	return $val;
}